#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SQL type wrappers audited by Joshua Kugler, 2008-02-20
"""
This API references tmpo tables to provide a grapical display
of scheduled/non-conflicted events via the SIMILE/Timeline
software. Please refer to http://simile.mit.edu/timeline/ for
reference material on SIMILIE/Timeline javascript code
"""
from time import strftime, strptime
from tack.db import query
from tack.lib import content_headers, status_codes, json_app
from tack.lib.dicttools import query_to_list
import time

select_info = """
SELECT
    ts.start,
    ts.finish,
    td.name,
    tvt.vt_description,
    ts.location_pickup,
    ts.location_delivery,
    tvt.vt_image_url
FROM
    tmpo_schedule_resourced ts,
    tmpo_vehicle tv,
    tmpo_vehicle_type tvt,
    tmpo_driver td
WHERE
    ts.start >= getdate()-90
    AND ts.finish <= getdate()+90
    AND ts.vehicle_id=tv.vehicle_id
    AND tvt.vt_id=tv.type
    AND td.driver_id=ts.driver_id
"""


def simile_time(t):
    return strftime("%b %d %Y %H:%M:%S",
        strptime(str(t), "%Y-%m-%d %H:%M:%S"))

def timeline(environ, start_response):
    output = {'events':[]}
    events = output['events']
    rows = query(environ['connection'], select_info)
    for row in rows:
        tmp_event = {
             'isDuration':'true',
             'start':simile_time(row[0]),
             'end':simile_time(row[1]),
             'title':str(row[2])+" - "+str(row[3]),
             'description':str(row[4])+" - "+str(row[5]),
             'icon':str(row[6])
             }
        events.append(tmp_event)
    return json_app(output)(environ, start_response)
